package org.alfresco.rfernandes.zkcmis.login;

import java.util.HashMap;
import java.util.Map;

import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.enums.BindingType;

public class CMISUtil {

	// Create a SessionFactory and set up the SessionParameter map
	private SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
	private Map<String, String> parameter = new HashMap<String, String>();
	private Repository repository;
	private Session session = null;

	public CMISUtil(String url, String user, String password,boolean useAlfrescoFactory) {
		parameter.put(SessionParameter.ATOMPUB_URL, url);
		parameter.put(SessionParameter.BINDING_TYPE,
				BindingType.ATOMPUB.value());
		// set the object factory
		if(useAlfrescoFactory)
			parameter.put(SessionParameter.OBJECT_FACTORY_CLASS,"org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
		parameter.put(SessionParameter.USER, user);
		parameter.put(SessionParameter.PASSWORD, password);
		// find all the repositories at this URL - there should only be one.
		repository = sessionFactory.getRepositories(parameter).get(0);
	}

	public Repository getRepository() {
		return repository;
	}

	public Session connect() {
		// create session with the first (and only) repository
		parameter.put(SessionParameter.REPOSITORY_ID, repository.getId());
		session = sessionFactory.createSession(parameter);
		return session;
	}

}